package model

import (
	"fmt"
	"gitee.com/whilew/gen-go/pkg/cmd/env"
	"gitee.com/whilew/gen-go/pkg/genericiooptions"
	"gitee.com/whilew/gen-go/pkg/resource"
	"gitee.com/whilew/gen-go/pkg/util"
	"github.com/spf13/cobra"
	"strings"
)

type ModelOptions struct {
	DSN           string
	TemplatePath  string
	FileDir       string
	TablePrefix   []string
	WithoutPrefix []string
	IsSplit       bool
	genericiooptions.IOStreams
}

func NewModelOptions(ioStreams genericiooptions.IOStreams) *ModelOptions {
	return &ModelOptions{
		IOStreams: ioStreams,
	}
}

func NewCmdModel(ioStreams genericiooptions.IOStreams) *cobra.Command {
	o := NewModelOptions(ioStreams)

	cmd := &cobra.Command{
		Use:                   "model [-dsn DSN] [-T Template] [-f FileDir] [-t TABLE_PREFIX] [-w WITHOUT_PREFIX] [-split]",
		DisableFlagsInUseLine: true,
		Short:                 "generate model code from mysql",
		Run: func(cmd *cobra.Command, args []string) {
			fmt.Println("model Run")
			var tablePrefix []string
			for _, prefix := range o.TablePrefix {
				tablePrefix = append(tablePrefix, strings.Split(prefix, ",")...)
			}
			o.TablePrefix = tablePrefix
			util.CheckError(o.RunCreate(args))
		},
	}

	cmd.Flags().StringVarP(&o.DSN, "dsn", "d", "", "mysql dsn")
	cmd.Flags().StringVarP(&o.TemplatePath, "template", "T", "", "template path")
	cmd.Flags().StringVarP(&o.FileDir, "filedir", "f", "", "file path")
	cmd.Flags().StringArrayVarP(&o.TablePrefix, "table-prefix", "t", []string{}, "table prefix")
	cmd.Flags().StringArrayVarP(&o.WithoutPrefix, "without-prefix", "w", []string{}, "without prefix")
	cmd.Flags().BoolVarP(&o.IsSplit, "split", "s", false, "split file")

	return cmd
}

func (o *ModelOptions) RunCreate(args []string) error {
	if o.DSN == "" {
		o.DSN = env.GEN_MYSQL_DSN
	}
	if o.DSN == "" {
		return fmt.Errorf("dsn is empty")
	}
	genModelVisitor := newModelTemplateVisitor()
	if o.IsSplit {
		genModelVisitor.WithSplit()
		//b.WithVisitorFunc(GenModelBySplitTemplateFile("./example/model"))
	}
	if o.FileDir != "" {
		genModelVisitor.WithGenDir(o.FileDir)
	}
	if o.TemplatePath != "" {
		genModelVisitor.WithTemplateFile(o.TemplatePath)
		//b.WithVisitorFunc(GenModelByDefaultTemplateFile(o.FilePath))
	}

	r := resource.NewBuilder().
		WithVisitorFunc(resource.SetModeInfoByMySqlDsn(o.DSN, o.TablePrefix, o.WithoutPrefix)).
		WithVisitorFunc(genModelVisitor.Visit()).
		Do()

	err := r.Err()
	if err != nil {
		return err
	}

	err = r.Visit(resource.CreateFile())
	return err
}
